package com.tgy.helloworld.service;



import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/***
 * @ClassName: News
 * @Description:
 * @Auther: tanggy3
 * @Date: 10:15 2023/6/30
 * @version : V1.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class News {
    private final RestTemplate restTemplate;

    /**
     * 调用插入方法 插入成功返回1，
     * @return
     * @throws UnsupportedEncodingException
     */
    public Integer add(NewsDTO newsDTO) throws UnsupportedEncodingException {
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String cookie = "cookie";
        String cookieV = "JIDENTITY=8a44c2f5-9339-4bd3-830b-ecc6a34bc9a2; JSESSIONID=CA36B7C5CD8C74211884B59F66B32852";
        String site = "Siteid";
        String siteV = newsDTO.getSiteId(); //需要修改为默认指定的站点!!!!
        headers.add(site, siteV);
        headers.add(cookie, cookieV);
        JSONObject post = JSONObject.parseObject("{\"json\":{\"pics\":[],\"xinwenliebiaotu\":\"\",\"xinwenfenxiangtu\":\"\",\"shoujibannertu\":\"\",\"shoujiliebiaotu\":\"\",\"biaotitu\":\"\",\"neirongtu\":\"\",\"leixingtu\":\"\",\"txt3\":\"JTNDcCUzRTExMTElM0MvcCUzRQ==\"},\"modelId\":912,\"modelName\":\"新闻\",\"channelId\":2341,\"title\":{\"titleColor\":\"#666666\",\"titleIsBold\":true,\"title\":\"你好你好你好\"},\"shortTitle\":\"1111\",\"releaseTime\":\"2023-06-30 09:55:22\",\"author\":\"\",\"description\":\"1111\",\"resource\":\"\",\"contentSourceId\":{\"sourceLink\":\"\",\"sourceName\":\"人民网\"},\"contentTag\":\"\",\"releaseTerrace\":[\"releasePc\",\"releaseWap\",\"releaseApp\",\"releaseMiniprogram\"],\"tplPc\":\"\",\"tplMobile\":\"\",\"allowComment\":1,\"viewControl\":1,\"outLink\":{\"isNewTarget\":false,\"outLink\":\"\"},\"\":\"\",\"type\":5}");


        //入参字段里面的json
        JSONObject json = JSONObject.parseObject( "{\"pics\":[],\"xinwenliebiaotu\":\"\",\"xinwenfenxiangtu\":\"\",\"shoujibannertu\":\"\",\"shoujiliebiaotu\":\"\",\"biaotitu\":\"\",\"neirongtu\":\"\",\"leixingtu\":\"\",\"txt3\":\"JTNDcCUzRTExMTElM0MvcCUzRQ==\"}");
        //json.put("pics",new JSONArray());  //暂时用不到图片上传
        String s = webCode(newsDTO.getContent());//进行编码
        json.put("text3",s);//编码后的值


        //入参字段里面的title
        JSONObject title = JSONObject.parseObject("{\"titleColor\":\"#666666\",\"titleIsBold\":true,\"title\":\"你好你好你好\"}");
        title.put("title",newsDTO.getTitle());



        post.put("title",title);
        post.put("json",json);
        post.put("shortTitle","短标题");
        post.put("description",newsDTO.getDescription());

        HttpEntity<String> entity = new HttpEntity<String>(post.toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://220.179.8.182:8080//cmsmanager/content", entity, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if(jsonObject.get("code").equals(200)){
            return 1;
        }else {
            return 0;
        }
    }


    /**
     * 编码方法
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String webCode(String str) throws UnsupportedEncodingException {
        String urlStr = URLEncoder.encode(str, "UTF-8")
                .replaceAll("\\+", "%20")
                .replaceAll("\\%21", "!")
                .replaceAll("\\%27", "'")
                .replaceAll("\\%28", "(")
                .replaceAll("\\%29", ")")
                .replaceAll("\\%7E", "~")
                .replaceAll("\\%2C", ",")
                .replaceAll("\\%2F", "/")
                .replaceAll("\\%3F", "?")
                .replaceAll("\\%3A", ":")
                .replaceAll("\\%40", "@")
                .replaceAll("\\%26", "&")
                .replaceAll("\\%3D", "=")
                .replaceAll("\\%2B", "+")
                .replaceAll("\\%24", "\\$")
                .replaceAll("\\%23", "#");
        String base64encodedString = Base64.getEncoder().encodeToString(urlStr.getBytes("ASCII"));
        //System.out.println(urlStr);
        //System.out.println(base64encodedString);
        return base64encodedString;
    }


    /**
     * 批处理方法
     */
    public void deal(){
        /**
         * // TODO: 2023/6/30 等待化工学院提供表结构以及数据  其中还得区分各个数据放入的子站，因为设计到siteId
         * 1、从数据库拿出新闻数据
         * 2、把需要的新闻呃数据（标题内容等）放入参数中
         * 3、调用插入方法。把处理数量加一
         *
         */
        List<NewsDTO> list = new ArrayList<>(5);



        for (int i = 0; i < 5; i++) {
            NewsDTO build = NewsDTO.builder().description("批量描述").title("批量标题" + i).content("内容").siteId("102").build();
            list.add(build);
        }


        AtomicReference<Integer> sum = new AtomicReference<>(0);
        list.forEach((bean)->{
            try {
                Integer add = add(bean);
                if(add.equals(0)){
                    throw new Exception("接口错误");
                }
                sum.updateAndGet(v -> v + add);
            } catch (Exception e) {
                log.info("处理数量为{}", sum);
                log.error(e.getMessage());
            }
        });
        log.info("处理数量为{}", sum);
    }



    public Integer add() throws UnsupportedEncodingException {
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String cookie = "cookie";
        String cookieV = "JIDENTITY=8a44c2f5-9339-4bd3-830b-ecc6a34bc9a2; JSESSIONID=CA36B7C5CD8C74211884B59F66B32852";
        String site = "Siteid";
        String siteV = "102"; //需要修改为默认指定的站点!!!!
        headers.add(site, siteV);
        headers.add(cookie, cookieV);
        JSONObject post = JSONObject.parseObject("{\"json\":{\"pics\":[],\"xinwenliebiaotu\":\"\",\"xinwenfenxiangtu\":\"\",\"shoujibannertu\":\"\",\"shoujiliebiaotu\":\"\",\"biaotitu\":\"\",\"neirongtu\":\"\",\"leixingtu\":\"\",\"txt3\":\"JTNDcCUzRTExMTElM0MvcCUzRQ==\"},\"modelId\":912,\"modelName\":\"新闻\",\"channelId\":2341,\"title\":{\"titleColor\":\"#666666\",\"titleIsBold\":true,\"title\":\"你好你好你好\"},\"shortTitle\":\"1111\",\"releaseTime\":\"2023-06-30 09:55:22\",\"author\":\"\",\"description\":\"1111\",\"resource\":\"\",\"contentSourceId\":{\"sourceLink\":\"\",\"sourceName\":\"人民网\"},\"contentTag\":\"\",\"releaseTerrace\":[\"releasePc\",\"releaseWap\",\"releaseApp\",\"releaseMiniprogram\"],\"tplPc\":\"\",\"tplMobile\":\"\",\"allowComment\":1,\"viewControl\":1,\"outLink\":{\"isNewTarget\":false,\"outLink\":\"\"},\"\":\"\",\"type\":5}");


        //入参字段里面的json
        JSONObject json = JSONObject.parseObject( "{\"pics\":[],\"xinwenliebiaotu\":\"\",\"xinwenfenxiangtu\":\"\",\"shoujibannertu\":\"\",\"shoujiliebiaotu\":\"\",\"biaotitu\":\"\",\"neirongtu\":\"\",\"leixingtu\":\"\",\"txt3\":\"JTNDcCUzRTExMTElM0MvcCUzRQ==\"}");
        //json.put("pics",new JSONArray());  //暂时用不到图片上传
        String s = webCode("你好");//进行编码
        json.put("text3",s);//编码后的值


        //入参字段里面的title
        JSONObject title = JSONObject.parseObject("{\"titleColor\":\"#666666\",\"titleIsBold\":true,\"title\":\"你好你好你好\"}");
        title.put("title","你好");



        post.put("title",title);
        post.put("json",json);
        post.put("shortTitle","短标题");
        post.put("description","描述");

        HttpEntity<String> entity = new HttpEntity<String>(post.toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://220.179.8.182:8080//cmsmanager/content", entity, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if(jsonObject.get("code").equals(200)){
            return 1;
        }else {
            return 0;
        }
    }

}
